package com.etl.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.cli.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 *  CommandLine-Util
 *
 * User: Locker1995
 * Date: 2018-04-18
 * Time: 9:32 AM
 */
public class CommandLineUtil {

    public static JSONObject getArgs(String[] args, Options options,String appName){

        HelpFormatter hf = new HelpFormatter();
        hf.setWidth(110);
        CommandLine commandLine = null;
        CommandLineParser parser = new PosixParser();
        JSONObject argsJson = new JSONObject();
        try {
            commandLine = parser.parse(options, args);
            if (commandLine.hasOption('h')) {
                // 打印使用帮助
                hf.printHelp(appName, options, true);
            }
            // 打印opts的名称和值
            System.out.println("--------------------------------------");
            Option[] opts = commandLine.getOptions();
            if (opts != null) {
                for (Option opt1 : opts) {
                    String name = opt1.getLongOpt();
                    String value = commandLine.getOptionValue(name);
                    argsJson.put(name, value);
                }
            }
        } catch (ParseException e) {
            hf.printHelp(appName, options, true);
        }
        return argsJson;
    }

}
